package cn.regexp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.regexp.domain.*;
import cn.regexp.mapper.OrderGoodsMapper;
import cn.regexp.mapper.OrderMapper;
import cn.regexp.query.OrderQuery;
import cn.regexp.service.ICartService;
import cn.regexp.service.IGoodsService;
import cn.regexp.service.IOrderService;
import cn.regexp.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, ShopOrder> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IGoodsService goodsService;

    @Override
    @Transactional
    public ShopOrder createOrder(List<ShopOrderGoods> goods, ShopConsignee consignee, Integer type, ShopUser shopUser) {
        ShopOrder order = new ShopOrder();
        try {
            DateTime orderTime = DateUtil.date();
            // TODO 查询窗口打包和配送费用
            if (ShopOrder.TYPE_DELIVERY.equals(type)) {
                order.setOrderSn("PS" + generateOrderSn(orderTime));
            } else if (ShopOrder.TYPE_SELF_PICK_UP.equals(type)) {
                order.setOrderSn("ZQ" + generateOrderSn(orderTime));
            }
            order.setUserId(consignee.getUserId());
            order.setType(ShopOrder.TYPE_DELIVERY);
            order.setConsigneeId(consignee.getId());
            order.setOrderState(ShopOrder.ORDER_ARREARAGE);
            order.setPayState(ShopOrder.PAY_ARREARAGE);
            order.setRemark("");
            order.setMobile(consignee.getConsigneeMobile());

            BigDecimal goodsPrice = BigDecimal.ZERO;
            order.setGoodsPrice(goodsPrice);
            goods.forEach(item -> order.setGoodsPrice(order.getGoodsPrice().add(item.getGoodsPrice())));
            order.setPackPrice(BigDecimal.ZERO);
            order.setFreightPrice(BigDecimal.ZERO);
            order.setOrderPrice(order.getGoodsPrice().add(order.getPackPrice()).add(order.getFreightPrice()));
            order.setOrderTime(orderTime);
            orderMapper.insert(order);

            // 保存订单商品信息
            goods.forEach(item -> {
                // 更改购物车商品状态为已支付
                UpdateWrapper<ShopCart> cartUpdateWrapper = new UpdateWrapper<>();
                cartUpdateWrapper.set("is_pay", ShopCart.YES)
                        .eq("user_id", shopUser.getId())
                        .eq("goods_id", item.getGoodsId());
                cartService.update(cartUpdateWrapper);
                // 增加商品销量
                ShopGoods goods1 = goodsService.getById(item.getGoodsId());
                goods1.setSaleNum(goods1.getSaleNum() + 1);
                goodsService.updateById(goods1);

                item.setOrderId(order.getId());
                item.setOrderSn(order.getOrderSn());
                orderGoodsMapper.insert(item);
            });
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return order;
    }

    /**
     * 生成订单的编号order_sn
     *
     * @param orderTime 下单时间
     */
    public static String generateOrderSn(DateTime orderTime) {
        return DateUtils.format(orderTime, DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS);
    }


    @Override
    @SuppressWarnings("unchecked")
    public IPage<ShopOrder> queryOrder(OrderQuery qo) {
        IPage<ShopOrder> shopOrderPage = new Page<>(qo.getPageNum(), 100);
        QueryWrapper<ShopOrder> wrapper = new QueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(qo.getOrderState()) && -1 != qo.getOrderState(),
                        "order_state", qo.getOrderState())
                .eq("user_id", qo.getUserId()).orderByDesc("order_time");
        IPage<ShopOrder> shopOrderIPage = super.page(shopOrderPage, wrapper);
        List<ShopOrder> shopOrderList = shopOrderIPage.getRecords();
        shopOrderList.forEach(item -> {
            QueryWrapper<ShopOrderGoods> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_sn", item.getOrderSn());
            item.setShopOrderGoodsList(orderGoodsMapper.selectList(wrapper1));
        });
        shopOrderIPage.setRecords(shopOrderList);
        return shopOrderIPage;
    }

    @Override
    public ShopOrder getOrderByOrderSn(String orderSn) {
        QueryWrapper<ShopOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);


        List<Integer> list = Arrays.asList(1, 2, 1, 3, -1, 2, 4);
        Optional<Integer> first = list.stream().findFirst();
        if (first.isPresent()) {
            System.out.println("返回第一个元素:" + first.get());
        }
        // 更优雅的方式
        first.ifPresent(integer -> System.out.println("返回第一个元素:" + integer));

        Optional<Integer> anyEle = list.stream().findAny();
        System.out.println(anyEle.get());


        return super.getOne(wrapper);
    }





















    private static final int[] POWER = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    public static void main(String[] args) {
        List<String> idList = new ArrayList<>();
        String partId = "44092119980525";
        for (int i = 0; i < 1000; i++) {
            String tempId = "";
            if (i % 2 == 0) {
                if (i < 10) {
                    tempId = partId + "00" + i;
                } else if (i < 100) {
                    tempId = partId + "0" + i;
                } else {
                    tempId = partId + i;
                }
                char checkCode18 = getCheckCode18(tempId);
                idList.add(tempId + checkCode18);
            }
        }

        String url = "http://kzp.mof.gov.cn/acc/system/base/getPwdQuestion?idNum=";
        Collections.reverse(idList);
        for (String id : idList) {
            String content = HttpUtil.get(url + id);
            System.out.println(content);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        // idList.forEach(System.out::println);

    }

    private static char getCheckCode18(String code17) {
        int sum = getPowerSum(code17.toCharArray());
        return getCheckCode18(sum);
    }


    private static char getCheckCode18(int iSum) {
        switch (iSum % 11) {
            case 10:
                return '2';
            case 9:
                return '3';
            case 8:
                return '4';
            case 7:
                return '5';
            case 6:
                return '6';
            case 5:
                return '7';
            case 4:
                return '8';
            case 3:
                return '9';
            case 2:
                return 'X';
            case 1:
                return '0';
            case 0:
                return '1';
            default:
                return StrUtil.C_SPACE;
        }
    }

    private static int getPowerSum(char[] iArr) {
        int iSum = 0;
        if (POWER.length == iArr.length) {
            for (int i = 0; i < iArr.length; i++) {
                iSum += Integer.parseInt(String.valueOf(iArr[i])) * POWER[i];
            }
        }
        return iSum;
    }
}

















